<?php

/**
 * @Author: kaihui.wang
 * @Contact  hpuwang@gmail.com
 * @Version: 1.0.0
 * @Date: 2020/10/21 14:14
 */

namespace Eduxplus\WebsiteBundle\Service;


use Eduxplus\CoreBundle\Lib\Base\AppBaseService;
use Eduxplus\CoreBundle\Lib\Service\HelperService;
use Knp\Component\Pager\PaginatorInterface;
use Eduxplus\CmsBundle\Entity\CmsNewsFav;

class NewsService extends AppBaseService
{
    protected $helperService;
    protected $paginator;

    public function __construct(HelperService $helperService, PaginatorInterface $paginator)
    {
        $this->helperService = $helperService;
        $this->paginator = $paginator;
    }

    public function getTopNews($limit = 9)
    {
        $sql = "SELECT a FROM Cms:CmsNews a WHERE a.status=1 ORDER BY a.createdAt DESC";
        $result = $this->db()->fetchAll($sql, [], 0, $limit);
        if (!$result) return $result;
        $newsIds = [];
        foreach ($result as &$v) {
            $v['createdAtTime'] = $v["createdAt"]->getTimestamp();
            $newsIds[] = $v['id'];
        }

        if ($newsIds) {
            $mainSql = "SELECT a FROM Cms:CmsNewsMain a WHERE a.newsId IN (:newsIds)";
            $mainDetail = $this->db()->fetchAll($mainSql, ["newsIds" => $newsIds]);
            foreach ($result as &$v) {
                foreach ($mainDetail as $dv) {
                    if ($dv['newsId'] == $v['id']) {
                        $v['main'] = $dv;
                    }
                }
            }
        }
        return $result;
    }


    public function getAllNewsFirstCategory()
    {
        $sql = "SELECT a FROM Cms:CmsNewsCategory a WHERE a.isShow =1 AND a.parentId = 0 ORDER BY a.sort DESC";
        $category = $this->db()->fetchAll($sql);
        return $category;
    }

    public function viewNumIncre($id)
    {
        $sql = "UPDATE Cms:CmsNews a SET a.viewNumber = a.viewNumber+1 WHERE a.id = :id ";
        $this->db()->execute($sql, ["id" => $id]);
    }

    public function favNumIncre($id)
    {
        $sql = "UPDATE Cms:CmsNews a SET a.favNumber = a.favNumber+1 WHERE a.id = :id ";
        $this->db()->execute($sql, ["id" => $id]);
    }


    public function favNumDecre($id)
    {
        $sql = "UPDATE Cms:CmsNews a SET a.favNumber = a.favNumber-1 WHERE a.id = :id AND a.favNumber>0";
        $this->db()->execute($sql, ["id" => $id]);
    }

    /**
     *
     * @param $topValue 0-最新，1-最热，2-加精/精选
     */
    public function getNewsByTopValue($topValue, $limit = 6)
    {
        $sql = "SELECT a FROM Cms:CmsNews a WHERE a.status=1 AND a.topValue = :topValue ORDER BY a.sort DESC, a.createdAt DESC";
        $result = $this->db()->fetchAll($sql, ["topValue" => $topValue], 0, $limit);
        if (!$result) return $result;
        $newsIds = [];
        foreach ($result as &$v) {
            $v['createdAtTime'] = $v["createdAt"]->getTimestamp();
            $newsIds[] = $v['id'];
        }

        if ($newsIds) {
            $mainSql = "SELECT a FROM Cms:CmsNewsMain a WHERE a.newsId IN (:newsIds)";
            $mainDetail = $this->db()->fetchAll($mainSql, ["newsIds" => $newsIds]);
            foreach ($result as &$v) {
                foreach ($mainDetail as $dv) {
                    if ($dv['newsId'] == $v['id']) {
                        $v['main'] = $dv;
                    }
                }
            }
        }
        return $result;
    }

    public function getNewsByCategory($categoryId, $limit = 3)
    {
        $sql = "SELECT a FROM Cms:CmsNews a WHERE a.status=1 AND a.firstCategoryId = :firstCategoryId ORDER BY a.sort DESC, a.createdAt DESC";
        $result = $this->db()->fetchAll($sql, ["firstCategoryId" => $categoryId], 0, $limit);
        if (!$result) return $result;
        foreach ($result as &$v) {
            $v['createdAtTime'] = $v["createdAt"]->getTimestamp();
        }
        return $result;
    }

    /**
     * $topValue 0-最新，1-最热，2-精选
     */
    public function getNewsList($category, $topValue, $page, $pageSize)
    {

        $em = $this->getDoctrine()->getManager();
        $em = $this->db()->enableSoftDeleteable($em);

        $parameters = [];
        if ($category) {
            $dql = "SELECT a FROM Cms:CmsNews a WHERE a.status=1 AND a.firstCategoryId = :firstCategoryId ";
            $parameters["firstCategoryId"]= $category;
        } else {
            $dql = "SELECT a FROM Cms:CmsNews a WHERE a.status=1 ";
        }
        
        //最热或者加精
        if($topValue > 0){
            $dql = $dql."AND a.topValue = :topValue ORDER BY a.sort DESC, a.createdAt DESC";
            $parameters["topValue"]= $topValue;
        }else{
            //最新
            $dql = $dql." ORDER BY a.createdAt DESC ";
        }

        $query = $em->createQuery($dql);
        if ($parameters) $query = $query->setParameters($parameters);
        $pagination = $this->paginator->paginate(
            $query,
            $page,
            $pageSize
        );

        $items = $pagination->getItems();
        $itemsArr = [];
        $newsIds = [];
        if ($items) {
            foreach ($items as $v) {
                $vArr =  $this->toArray($v);
                $vArr['createdAtTime'] = strtotime($vArr["createdAt"]);
                $itemsArr[] = $vArr;
                $newsIds[] = $vArr['id'];
            }
        }

        // if ($newsIds) {
        //     $mainSql = "SELECT a FROM Cms:CmsNewsMain a WHERE a.newsId IN (:newsIds)";
        //     $mainDetail = $this->db()->fetchAll($mainSql, ["newsIds" => $newsIds]);
        //     foreach ($itemsArr as &$v) {
        //         foreach ($mainDetail as $dv) {
        //             if ($dv['newsId'] == $v['id']) {
        //                 $v['main'] = $dv;
        //             }
        //         }
        //     }
        // }

        return [$pagination, $itemsArr];
    }


    public function getById($id)
    {
        $dql = "SELECT a FROM Cms:CmsNews a WHERE a.id =:id ";
        $detail = $this->db()->fetchOne($dql, ["id" => $id]);
        if (!$detail) return $detail;
        $detail['createdAtTime'] = $detail["createdAt"]->getTimestamp();
        $detail['updatedAtTime'] = $detail["updatedAt"]->getTimestamp();
        $mainSql = "SELECT a FROM Cms:CmsNewsMain a WHERE a.newsId =:newsId ";
        $mainDetail = $this->db()->fetchOne($mainSql, ["newsId" => $id]);
        $detail['main'] = $mainDetail;
        return $detail;
    }

    
    public function getCategoryById($id)
    {
        $sql = "SELECT a FROM Cms:CmsNewsCategory a WHERE a.id =:id";
        $category = $this->db()->fetchOne($sql,["id" => $id]);
        return $category;
    }

    public function favList($uid, $page, $pageSize){
        $dql = "SELECT a FROM Cms:CmsNewsFav a WHERE a.uid =:uid";
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery($dql);
        $query= $query->setParameters(["uid"=>$uid]);
        $pagination = $this->paginator->paginate(
            $query,
            $page,
            $pageSize
        );
        
        $items = $pagination->getItems();
        $itemsArr = [];
        $newsIds = [];
        if ($items) {
            foreach ($items as $v) {
                $vArr =  $this->toArray($v);
                $newsIds[] = $vArr['newsId'];
            }
        }

        if ($newsIds) {
            $sql = "SELECT a FROM Cms:CmsNews a WHERE a.id IN (:id)";
            $itemsArr = $this->db()->fetchAllHard($sql, ["id" => $newsIds]);
            $mainSql = "SELECT a FROM Cms:CmsNewsMain a WHERE a.newsId IN (:newsIds)";
            $mainDetail = $this->db()->fetchAll($mainSql, ["newsIds" => $newsIds]);
            foreach ($itemsArr as &$v) {
                foreach ($mainDetail as $dv) {
                    if ($dv['newsId'] == $v['id']) {
                        $v['createdAtTime'] = $v["createdAt"]->getTimestamp();
                        $v['main'] = $dv;
                        $isDelete = is_null($v["deletedAt"])?0:1;
                        if(!$isDelete){
                            $isDelete = $v["status"]?0:1;
                        }
                        $v['isDelete'] = $isDelete;
                    }
                }
            }
        }
        return [$pagination, $itemsArr];
    }

    /**
     * 获取收藏
     * @param $goodsId
     * @param $uid
     */
    public function getFav($id, $uid){
        $sql = "SELECT a FROM Cms:CmsNewsFav a WHERE a.uid=:uid AND a.newsId =:newsId ";
        return $this->db()->fetchOne($sql, ["uid"=>$uid, "newsId"=>$id]);
    }


    /**
     * 删除收藏
     *
     * @param $goodsId
     * @param $uid
     * @return bool
     */
    public function delFav($id, $uid){
        $sql = "SELECT a FROM Cms:CmsNewsFav a WHERE a.uid=:uid AND a.newsId =:newsId ";
        $model =  $this->db()->fetchOne($sql, ["uid"=>$uid, "newsId"=>$id], 1);
        return $this->db()->hardDelete($model);
    }

    /**
     * 收藏商品
     * @param $goodsId
     * @param $uid
     */
    public function addFav($id, $uid){
        $model = new CmsNewsFav();
        $model->setNewsId($id);
        $model->setUid($uid);
        return $this->db()->save($model);
    }


    public function clearFailure($uid){
        $sql = "SELECT a FROM Cms:CmsNewsFav a LEFT JOIN Cms:CmsNews b WITH a.newsId =b.id WHERE a.uid =:uid AND ( b.status =0 OR b.deletedAt is not null )";
        $itemsArr = $this->db()->fetchAllHard($sql, ["uid" => $uid], 1);
        $this->db()->delete($itemsArr);
    }

}
